package com.alogic.xscript;

import com.alogic.xscript.plugins.Segment;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

/**
 * Namespace基类
 *
 * @since 1.6.12.42 [20190911]
 *
 * @version 1.6.13.23 [20201030 duanyy] <br>
 * - 优化xscript的日志机制  <br>
 */
public class Namespace extends Segment {
    protected Map<String,String> scripts = new HashMap<String,String>();

    public Namespace(String tag, Logiclet p) {
        super(tag, p);
    }

    public void registerModule(String xmltag,Class<? extends ExtensionTag> clazz,String src) {
        super.registerModule(xmltag, clazz);
        scripts.put(xmltag,src);
    }

    protected Logiclet createLogiclet(Class<? extends Logiclet> clazz,String xmlTag,Logiclet parent){
        try {
            if (ExtensionTag.class.isAssignableFrom(clazz)){
                String src = scripts.get(xmlTag);
                if (StringUtils.isNotEmpty(src)){
                    Constructor<? extends Logiclet> constructor = clazz.getConstructor(String.class, Logiclet.class,String.class);
                    return constructor.newInstance(new Object[]{xmlTag, parent,src});
                }else{
                    Constructor<? extends Logiclet> constructor = clazz.getConstructor(String.class, Logiclet.class);
                    return constructor.newInstance(new Object[]{xmlTag,parent});
                }
            }else {
                Constructor<? extends Logiclet> constructor = clazz.getConstructor(String.class, Logiclet.class);
                return constructor.newInstance(new Object[]{xmlTag, parent});
            }
        } catch (Exception e) {
            log(String.format("[%s]Can not create segment instance:%s",xmlTag,clazz.getName()),LOG_ERROR);
            return null;
        }
    }
}
